import {setGlobal} from '@swda/utils'

//-----------------------------------------------------------------------------
// SWDA_Window_Selectable_4Arrows
//
// The window class with cursor movement and scroll functions.

function SWDA_Window_Selectable_4Arrows() {
    this.initialize.apply(this, arguments);
}

// 继承自Window_Selectable
SWDA_Window_Selectable_4Arrows.prototype = Object.create(Window_Selectable.prototype);
SWDA_Window_Selectable_4Arrows.prototype.constructor = SWDA_Window_Selectable_4Arrows;

//=============================================================================
//【基本初始化、更新及参数】
//=============================================================================
SWDA_Window_Selectable_4Arrows.prototype.initialize = function(x, y, width, height) {
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
	this.opacity = 0;
	this.contentsOpacity = 0;
	this.x = this.x0();
	this.y = this.y0();
};

SWDA_Window_Selectable_4Arrows.prototype.visibleRows = function () {
    return 4;
}

SWDA_Window_Selectable_4Arrows.prototype.update = function() {
	//if(this._buttons){console.log(0,'!_!!!!!',this._buttons[0].enabled);}
    Window_Base.prototype.update.call(this);
	if (this._buttons)
		this.updateButtons();
    this.updateArrows();
    this.processCursorMove();
    this.processHandling();
	//this.processWheel();	//不处理滚轮
	this.processTouch();
    this._stayCount++;
	//if(this._buttons){console.log(0,'!_!!!!!-----',this._buttons[0].enabled);}
};
		

// 打开状态（按钮弹出）
SWDA_Window_Selectable_4Arrows.prototype.open = function() {
	if (this._buttons){
		this.initButtonsPosition(this._buttonCenterX,this._buttonCenterY);
	}
	Window_Base.prototype.open.call(this);

	
};
// 关闭状态（按钮淡出）
SWDA_Window_Selectable_4Arrows.prototype.updateClose = function() {
	if (this._closing) {
		this.updateButtonsOpacityClose();
		if (this.isClosed()) {
            this._closing = false;
        }
	}
	
};

SWDA_Window_Selectable_4Arrows.prototype.updateOpen = function() {
    if (this._opening) {
        this.openness += 32;
        if (this.isOpen()) {
            this._opening = false;
        }
    }
	this.refreshButtonsEnable();
};
//=============================================================================
//【窗口、按钮尺寸与位置】（隐藏窗口）
// 最小化窗口并移出屏幕外
//=============================================================================
// 窗口尺寸（隐藏原始窗口）
SWDA_Window_Selectable_4Arrows.prototype.windowWidth = function() {
    return 0;
};

SWDA_Window_Selectable_4Arrows.prototype.windowHeight = function() {
    return 0;
};

//窗口坐标（用于隐藏原始窗口，会被补偿掉）
SWDA_Window_Selectable_4Arrows.prototype.x0 = function(){
	return -50;
}
//窗口坐标（用于隐藏原始窗口，会被补偿掉）
SWDA_Window_Selectable_4Arrows.prototype.y0 = function(){
	return -50;
}

//=============================================================================
//【按钮尺寸】
//=============================================================================
SWDA_Window_Selectable_4Arrows.prototype.buttonWidth = function(){
	return 192;
}
SWDA_Window_Selectable_4Arrows.prototype.buttonHeight = function(){
	return 96;
}
//=============================================================================
//【按钮更新帧数】
//=============================================================================
SWDA_Window_Selectable_4Arrows.prototype.updateFrameNum = function(){
	return 13;
}

//=============================================================================
//【按钮不透明度、可见性的初始化与更新】
//=============================================================================
// 按钮透明度初始化
SWDA_Window_Selectable_4Arrows.prototype.initButtonsOpacity = function(){
	this._buttons[0].opacity = 0;
	this._buttons[1].opacity = 0;
	this._buttons[2].opacity = 0;
	this._buttons[3].opacity = 0;
}
// 按钮透明度更新（出现）
SWDA_Window_Selectable_4Arrows.prototype.updateButtonsOpacity = function() {
	if(!this._closing){
		var opacitySpeed = 255 / this.updateFrameNum();
		for (var i=0; i<4; i++){
			if (this._buttons[i].opacity < 255)
				this._buttons[i].opacity += opacitySpeed;
		}
	}
};
// 按钮透明度更新（关闭）
SWDA_Window_Selectable_4Arrows.prototype.updateButtonsOpacityClose = function() {
	var opacitySpeed = 255 / this.updateFrameNum();
	for (var i=0; i<4; i++){
		if (this._buttons[i].opacity > 0)
			this._buttons[i].opacity -= opacitySpeed;
	}
	this.openness -= opacitySpeed;
};
// 按钮可见
SWDA_Window_Selectable_4Arrows.prototype.updateButtonsVisiblity = function() {
    if (TouchInput.date > Input.date) {
        this.showButtons();
    } else {
        this.hideButtons();
    }
};
// 按钮不可见
SWDA_Window_Selectable_4Arrows.prototype.showButtons = function() {
    for (var i = 0; i < this._buttons.length; i++) {
        this._buttons[i].visible = true;
    }
};

SWDA_Window_Selectable_4Arrows.prototype.hideButtons = function() {
    for (var i = 0; i < this._buttons.length; i++) {
        this._buttons[i].visible = false;
    }
};

SWDA_Window_Selectable_4Arrows.prototype.refresh = function() {
	Window_Selectable.prototype.refresh.call(this);
	this.refreshButtonsEnable();
};

//=============================================================================
//【创建按钮】
// 重要：在Scene中使用！
//=============================================================================
SWDA_Window_Selectable_4Arrows.prototype.createButtons = function(buttonImage, x, y) {	
    var bitmap = ImageManager.loadBitmap('img/system/UI/', buttonImage);
	this.setButtonCenterCoord(x,y);
	// 按钮宽高及环绕中心坐标
	var bW = this.buttonWidth();
	var bH = this.buttonHeight();
    this._buttons = [];
	
	// 划分按钮sprite
	for (var i = 0; i < 4; i++) {
        var button = new Sprite_Button();
        var sx = bW * i;
        var sw = bW * (i === 4 ? 2 : 1);	
        button.bitmap = bitmap;
        button.setColdFrame(sx, 0, sw, bH);
        button.setHotFrame(sx, bH, sw, bH);
		button.setOnFrame(sx, 2*bH, sw, bH);
        button.visible = true;
		/*
		if (this._list[i].symbol != '')	//
			button.enabled = this._list[i].enabled;
			*/
        this._buttons.push(button);
		
        this.addChild(button);
    }
	
	// 初始化按钮坐标
	this.initButtonsPosition(x,y);
	
	// 执行命令的Handler
	if (this._list[0].symbol != '')
		this._buttons[0].setClickHandler(this.onButtonUp.bind(this));
    if (this._list[1].symbol != '')
		this._buttons[1].setClickHandler(this.onButtonLeft.bind(this));
    if (this._list[2].symbol != '')
		this._buttons[2].setClickHandler(this.onButtonDown.bind(this));
    if (this._list[3].symbol != '')
		this._buttons[3].setClickHandler(this.onButtonRight.bind(this));
};

//=============================================================================
//【更新按钮位置】
//=============================================================================
// 设置按钮组中心点坐标值
SWDA_Window_Selectable_4Arrows.prototype.setButtonCenterCoord = function(x, y){
	this._buttonCenterX = (x || 450) - this.x0();
	this._buttonCenterY = (y || 200) - this.y0();
}

// 初始化按钮位置
SWDA_Window_Selectable_4Arrows.prototype.initButtonsPosition = function(x, y){
	
	var cX = this._buttonCenterX;
	var cY = this._buttonCenterY;
	var bW = this.buttonWidth();
	var bH = this.buttonHeight();
	
	// 起始坐标
	this._buttons[0].x = cX - bW * 0.5;
	this._buttons[0].y = cY - bH * 0.5;
	
	this._buttons[1].x = cX - bW * 0.5;
	this._buttons[1].y = cY - bH * 0.5;
	
	this._buttons[2].x = cX - bW * 0.5;
	this._buttons[2].y = cY - bH * 0.5;
	
	this._buttons[3].x = cX - bW * 0.5;
	this._buttons[3].y = cY - bH * 0.5;
	
	
	// 最终坐标
	/*
	this._buttons[0].x = cX - bW * 0.5;
	this._buttons[0].y = cY - bH * 1.5;

	this._buttons[1].x = cX - bW - 24;
	this._buttons[1].y = cY - bH * 0.5;
	
	this._buttons[2].x = cX - bW * 0.5;
	this._buttons[2].y = cY + bH * 0.5;
	
	this._buttons[3].x = cX + 24;
	this._buttons[3].y = cY - bH * 0.5;
	*/
	this.initButtonsOpacity();
}
// 更新按钮可用性
SWDA_Window_Selectable_4Arrows.prototype.refreshButtonsEnable = function() {
	if (this._buttons){
		for (var i = 0; i < 4; i++) {
			if (this._list[i].symbol != ''){						//可选（有命令）但不一定可用
				this._buttons[i].enabled = this._list[i].enabled;
			}else{													//不可选（无命令）
				this._buttons[i].enabled = '';
			}
			if (i == this._index){
				this._buttons[i].onFrame();
			} else {
				this._buttons[i].updateFrame();
			}
		}
	}
};
// 更新按钮坐标（摊开按钮小动画）
SWDA_Window_Selectable_4Arrows.prototype.updateButtons = function() {
	//this.refreshButtonsEnable();
	var bW = this.buttonWidth();
	var bH = this.buttonHeight();
	var cX = this._buttonCenterX;
	var cY = this._buttonCenterY;
	var dx = 120 / this.updateFrameNum();	//13用于调节速度
	var dy = 96 / this.updateFrameNum();

	if (this._buttons[0].y > cY - bH * 1.5 + 0.01) {
		this._buttons[0].y -= dy;
	} else {
		this._buttons[0].y = cY - bH * 1.5;
	}
	
	if (this._buttons[1].x > cX - bW - 24 + 0.01) {
		this._buttons[1].x -= dx;
	} else {
		this._buttons[1].x = cX - bW - 24;
	}
	
	if (this._buttons[2].y < cY + bH * 0.5 - 0.01) {
		this._buttons[2].y += dy;
	} else {
		this._buttons[2].y = cY + bH * 0.5;
	}
	
	if (this._buttons[3].x < cX + 24 - 0.01) {
		this._buttons[3].x += dx;
	} else {
		this._buttons[3].x = cX + 24;
	}
	this.updateButtonsOpacity();
};

//=============================================================================
//【处理光标移动】
//=============================================================================
// 更新光标移动（键盘、鼠标输入）
SWDA_Window_Selectable_4Arrows.prototype.processCursorMove = function() {
    if (this.isCursorMovable()) {
        var lastIndex = this.index();
		// 更新图标
		if (TouchInput.movingdate < Input.date) {				//键盘输入的情况
			if (Input.isRepeated('up') && this._list[0].symbol != '') {
				this.cursorUp(Input.isTriggered('up'));
			}
			if (Input.isRepeated('left') && this._list[1].symbol != '') {
				this.cursorLeft(Input.isTriggered('left'));
			}
			if (Input.isRepeated('down') && this._list[2].symbol != '') {
				this.cursorDown(Input.isTriggered('down'));
			}
			if (Input.isRepeated('right') && this._list[3].symbol != '') {
				this.cursorRight(Input.isTriggered('right'));
			}
		
			// 如果当前index对应的指令不为空，则高亮，
			// 若不为空，则轮换查看哪个可用，切换到第一个可用的。
			if (this._list[this.index()].symbol != '') {
				this._buttons[this.index()].onFrame();
			} else {
				for (i = 0; (i < 4) && (!this._list[i].symbol != ''); i++) {}
				if (this._list[i].symbol != ''){
					this._buttons[i].onFrame();
					switch(i) {
					case 0:
						this.cursorUp(true);
						break;
					case 1:
						this.cursorLeft(true);
						break;
					case 2:
						this.cursorDown(true);
						break;
					case 3:
						this.cursorRight(true);
						break;
					default:
						this.cursorUp(true);
						break;
					} 
				}
			}
		} else {	//鼠标/触摸输入的情况
			if (this._list[0].symbol != '' && this._buttons[0].isMovedInsideFrame()){
				this.cursorUp(true);
			}
			if (this._list[1].symbol != '' && this._buttons[1].isMovedInsideFrame()){
				this.cursorLeft(true);
			}
			if (this._list[2].symbol != '' && this._buttons[2].isMovedInsideFrame()){
				this.cursorDown(true);
			}
			if (this._list[3].symbol != '' && this._buttons[3].isMovedInsideFrame()){
				this.cursorRight(true);
			}
			for (i = 0; i < 4; i++) {
				if (i == this._index){
					this._buttons[i].onFrame();
				} else {
					this._buttons[i].updateFrame();
				}
			}	
		}
		if (this.index() !== lastIndex) {
			SoundManager.playCursor();
		}
    }
};


SWDA_Window_Selectable_4Arrows.prototype.cursorUp = function(wrap) {
    this.select(0);
};

SWDA_Window_Selectable_4Arrows.prototype.cursorLeft = function(wrap) {
    this.select(1);
};

SWDA_Window_Selectable_4Arrows.prototype.cursorDown = function(wrap) {
    this.select(2);
};

SWDA_Window_Selectable_4Arrows.prototype.cursorRight = function(wrap) {
    this.select(3);
};


SWDA_Window_Selectable_4Arrows.prototype.processTouch = function() {
    if (this.isOpenAndActive()) {
        if (TouchInput.isCancelled()) {
            if (this.isCancelEnabled()) {
                this.processCancel();
            }
        }
    } else {
        this._touching = false;
    }
};

//=============================================================================
//【处理按钮响应】
//=============================================================================


SWDA_Window_Selectable_4Arrows.prototype.onButtonUp = function() {
	this.cursorUp();
	this.processOk();
};

SWDA_Window_Selectable_4Arrows.prototype.onButtonLeft = function() {
	this.cursorLeft();
	this.processOk();
};

SWDA_Window_Selectable_4Arrows.prototype.onButtonDown = function() {
	this.cursorDown();
	this.processOk();
};

SWDA_Window_Selectable_4Arrows.prototype.onButtonRight = function() {
	this.cursorRight();
	this.processOk();
};

setGlobal('SWDA_Window_Selectable_4Arrows',SWDA_Window_Selectable_4Arrows)